/* JimmApplication.java
 *
 * Copyright 2011-12 Aleksey Konovalov, r.u.s.h.a.n.
 * All Rights Reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 * 
 */

package org.jimm.app;

import java.util.ArrayList;
import org.jimm.protocol.AccountsManager;
import org.jimm.protocol.Contact;
import org.jimm.service.*;

import android.app.Activity;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

/**
 * @author Aleksey Konovalov, r.u.s.h.a.n.
 */
public class JimmApplication extends Application implements ServiceConnection {

    public static final String VERSION = "Android 0.1";
    private static final String LOG_TAG = "Jimm:JimmApplication";

    private static JimmApplication instance;
    private Preferences preferences;
    private Notifications notifications;
    private JimmService jimmService = null;

    public Context applicationContext;

    // ������� �������� ����������� �������
    private ArrayList<Runnable> serviceWaitQueue = new ArrayList<Runnable>();

    public ArrayList<Contact> chatPages = new ArrayList<Contact>();
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(LOG_TAG, "onCreate()");
    }

    private void startService() {
        if (jimmService == null) {
            Intent intent = new Intent(applicationContext, JimmService.class);
            // intent.setClass(applicationContext, JimmService.class);
            applicationContext.startService(intent);
            applicationContext.bindService(intent, this, 0);

            //applicationContext.bindService(intent, this, Context.BIND_AUTO_CREATE);

//			Intent intent = new Intent(applicationContext, JimmService.class);
////			Intent intent = new Intent(JimmService.ACTION_FOREGROUND);
////			intent.setClass(this, JimmService.class);
////			intent.setAction(JimmService.ACTION_FOREGROUND);
//			//startService(intent);
//			applicationContext.bindService(intent, jimmServiceConnection, Context.BIND_AUTO_CREATE);
        }
    }


    public void stopService(final Activity activity) {

        applicationContext.stopService(new Intent(applicationContext, JimmService.class));
        applicationContext.unbindService(this);

        activity.finish();
    }

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder service) {
        if (jimmService == null) {
            Log.i(LOG_TAG, "onServiceConnected()");
            jimmService = ((JimmService.LocalBinder) service).getService();
            synchronized (serviceWaitQueue) {
                for (Runnable r : serviceWaitQueue)
                    r.run();
                serviceWaitQueue.clear();
            }
            NotificationMan.updateNotifications(applicationContext);
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        Log.i(LOG_TAG, "onServiceDisconnected()");
        jimmService = null;
    }


    public static Context getContext() {
        return instance.applicationContext;
    }

    public JimmService getService() {
        return jimmService;
    }

    public static JimmApplication getInstance() {
        return instance;
    }

    public static JimmApplication getInstance(Context c) {
        if (instance == null) {
            instance = new JimmApplication();
            instance.onCreate();
            instance.applicationContext = c;
            instance.preferences = new Preferences(c);
            instance.notifications = new Notifications(c, instance.preferences);
            instance.startService();
        }
        return instance;
    }

    public Preferences getPreferences() {
        return preferences;
    }

    public Notifications getNotifications() {
        return notifications;
    }

    public AccountsManager getAccountsManager() {
        return jimmService.getAccountsManager();
    }

    public void callWhenServiceConnected(Runnable callback) {
        if (jimmService != null) {
            callback.run();
        } else {
            synchronized (serviceWaitQueue) {
                serviceWaitQueue.add(callback);
            }
        }
    }

    //////////////////////
    //                  //
    //    Clipboard     //
    //                  //
    //////////////////////

    private static String clipBoardText;
    private static String clipBoardHeader;
    private static boolean clipBoardIncoming;

    private static void insertQuotingChars(StringBuffer out, String text, char qChars) {
        int size = text.length();
        boolean wasNewLine = true;
        for (int i = 0; i < size; ++i) {
            char chr = text.charAt(i);
            if (wasNewLine) out.append(qChars).append(' ');
            out.append(chr);
            wasNewLine = (chr == '\n');
        }
    }

    public static boolean isClipBoardEmpty() {
        return null == clipBoardText;
    }

    public static String getClipBoardText(boolean quote) {
        if (isClipBoardEmpty()) {
            return "";
        }
        if (!quote || (null == clipBoardHeader)) {
            return clipBoardText + " ";
        }
        StringBuffer sb = new StringBuffer();
        sb.append('[').append(clipBoardHeader).append(']').append('\n');
        insertQuotingChars(sb, clipBoardText, clipBoardIncoming ? '\u00bb' : '\u00ab');//'�' : '�');
        sb.append("\n\n");
        return sb.toString();
    }

    public static void setClipBoardText(String header, String text) {
        //ClipData clip = ClipData.newPlainText(text);
        clipBoardText = text;
        clipBoardHeader = header;
        clipBoardIncoming = true;
    }

    public static void setClipBoardText(boolean incoming, String date, String from, String text) {
        clipBoardText = text;
        clipBoardHeader = from + ' ' + date;
        clipBoardIncoming = incoming;
    }

    public static void clearClipBoardText() {
        clipBoardText = null;
    }

}
